package com.lms.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.lms.bean.Root;
import com.lms.bean.User;
import com.lms.dao.BaseDao;
import com.lms.dao.apply.ApplyDao;
import com.lms.dao.apply.ApplyDaoImpl;
import com.lms.pojo.RootUserApplyData;
import com.lms.pojo.UserApplyData;
import com.lms.service.apply.ApplyService;
import com.lms.service.apply.ApplyServiceImpl;
import com.lms.service.lab.LabService;
import com.lms.service.lab.LabServiceImpl;
import com.lms.service.root.RootService;
import com.lms.service.root.RootServiceImpl;
import com.lms.service.user.UserService;
import com.lms.service.user.UserServiceImpl;
import com.lms.service.weixin.WeixinSerive;
import com.lms.service.weixin.WeixinSeriveImpl;
import com.lms.util.Constants;
import com.lms.util.WeixinUtil.WeixinConstants;
import com.lms.util.WeixinUtil.msg.WeixinPushMsg;
import com.lms.util.WeixinUtil.msg.WeixinPushMsgImpl;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RootServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=req.getParameter("method");
        if (method!=null){
            if (method.equals("getPersonalData")){
                this.getPersonalData(req,resp);
            }else if (method.equals("pwdModify")) {
                String oldpwd = req.getParameter("oldpwd");
                String newpwd = req.getParameter("newpwd");
                this.pwdModify(req, resp, oldpwd, newpwd);
            }else if (method.equals("getUserAccountList")){
                String userCode = req.getParameter("userCode");
                String role = req.getParameter("role");
                this.getUserAccountList(req, resp, userCode, role);
            }else if (method.equals("getApprovalMsg")){
                this.getApprovalMsg(req,resp);
            }else if (method.equals("setOpenState")){
                String labCode = req.getParameter("labCode");
                String week = req.getParameter("week");
                String interval = req.getParameter("interval");
                String state = req.getParameter("state");
                this.setOpenState(req,resp,labCode,week,interval,state);
            }else if (method.equals("getLabCodeByLabName")){
                String labName = req.getParameter("labName");
                this.getLabCodeByLabName(req,resp,labName);
            }else if (method.equals("refuse")){
                String applyID = req.getParameter("applyID");
                this.refuse(req,resp,applyID);
            }else if (method.equals("agree")){
                String applyID = req.getParameter("applyID");
                this.agree(req,resp,applyID);
            }else if (method.equals("reset")){
                String userCode = req.getParameter("userCode");
                this.reset(req,resp,userCode);
            }else if (method.equals("delete")){
                String userCode = req.getParameter("userCode");
                this.delete(req,resp,userCode);
            }else if (method.equals("getLabDataByLabName")){
                String labName = req.getParameter("labName");
                this.getLabDataByLabName(req,resp,labName);
            }else if (method.equals("setRootMsg")){
                String rootMsg = req.getParameter("rootMsg");
                String userCode = req.getParameter("userCode");
                this.setRootMsg(req,resp,userCode,rootMsg);
            }else if (method.equals("labModify")){
                String labName = req.getParameter("labName");
                String labTotal = req.getParameter("labTotal");
                String labTag = req.getParameter("labTag");
                String labIntroduce = req.getParameter("labIntroduce");
                this.labModify(req,resp,labName,labTotal,labTag,labIntroduce);
            }else if (method.equals("getApplyCount")){
                this.getApplyCount(req,resp);
            }else if (method.equals("downloadFile")){
                this.downloadFile(req,resp);
            }
            else {
                /*url有误，转发至error*/
                resp.sendRedirect(req.getContextPath() + "/error.jsp");
            }
        }
    }

    public void getPersonalData(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        Map<String,String> map=new HashMap<>();
        Root root=(Root) request.getSession().getAttribute(Constants.ROOT_SESSION);
        if (root!=null) {
            map.put("userCode", root.getUserCode());
            map.put("userName", root.getUserName());
            map.put("rootMsg", root.getRootMessage());
            map.put("rootGrade", root.getRootGrade() + "");
        }
        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }

    /*personal:密码修改*/
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp,String oldpwd,String newpwd) throws IOException {
        RootService rootService = new RootServiceImpl();
        Map<String,String> map=new HashMap<>();
        Root root = (Root) req.getSession().getAttribute(Constants.ROOT_SESSION);

        if (root!=null && root.getUserPassWord().equals(DigestUtils.md5Hex(Constants.SALT_HEAD+oldpwd+Constants.SALT_FOOT))) {
            if (rootService.updatePwd(root.getUserCode(), newpwd)) {
                map.put("ok","yes");
            } else {
                map.put("ok","no");
            }
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }

    /*userAdm:用户账号管理*/
    public void getUserAccountList(HttpServletRequest req, HttpServletResponse resp,String userCode,String role) throws IOException {
        List<User> userList=null;
        RootService rootService = new RootServiceImpl();
        Map<String,Object> map=new HashMap<>();

        userList=rootService.getUserAccountList(userCode,role);
        map.put("data",JSONArray.toJSON(userList));
        map.put("total",userList.size());

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }


    /*approval:申请审批*/
    public void getApprovalMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        RootService rootService = new RootServiceImpl();
        List<RootUserApplyData> rootUserApplyDataList=null;
        Map<String,Object> map=new HashMap<>();

        rootUserApplyDataList=rootService.getRootUserApplyDataList();
        map.put("data",JSONArray.toJSON(rootUserApplyDataList));
        map.put("total",rootUserApplyDataList.size());

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }

    /*labAdm:设置Open*/
    public void setOpenState(HttpServletRequest req, HttpServletResponse resp,String labCode,String week,String interval,String state) throws IOException {
        int res=0;
        RootService rootService = new RootServiceImpl();
        Map<String,Object> map = new HashMap<>();

        res = rootService.setOpenState(labCode, week, interval, state);
        if (res>0){
            map.put("success","yes");
        }else {
            map.put("success","no");
        }
        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }

    /*labAdm:由labName获取labCode*/
    public void getLabCodeByLabName(HttpServletRequest req, HttpServletResponse resp,String labName) throws IOException {
        LabService labService = new LabServiceImpl();
        Map<String,Object> map = new HashMap<>();

        map.put("labCode",labService.getLabCodeByLabName(labName));

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*approval：refuse*/
    public void refuse(HttpServletRequest req, HttpServletResponse resp,String applyID) throws IOException {
        RootService rootService = new RootServiceImpl();
        Map<String,Object> map = new HashMap<>();
        Root root = (Root) req.getSession().getAttribute(Constants.ROOT_SESSION);

        if (rootService.refuse(root.getUserCode(),applyID)>0){
            map.put("ok","yes");
            /*管理员完成审批操作，可以开始推送审批完成消息了
             * 1.判断是否绑定微信
             * 2.绑定了就推送消息*/
            WeixinPushMsg weixinPushMsg = new WeixinPushMsgImpl();
            ApplyDao applyDao = new ApplyDaoImpl();
            Connection connection= BaseDao.getConnection();
            try {
                Map<String,String> applyMsg = applyDao.getApplyMsg(connection, applyID);
                if (applyMsg.get("openID")!=null){
                    weixinPushMsg.push_approvalMsg(applyMsg.get("openID"), WeixinConstants.APPROVAL_TEMPLATE_ID,applyMsg.get("labName"),
                            applyMsg.get("applyCount"),applyMsg.get("applyTime"),false);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*approval：agree*/
    public void agree(HttpServletRequest req, HttpServletResponse resp,String applyID) throws IOException {
        RootService rootService = new RootServiceImpl();
        Map<String,Object> map = new HashMap<>();
        Root root = (Root) req.getSession().getAttribute(Constants.ROOT_SESSION);

        if (rootService.agree(root.getUserCode(),applyID)>0){
            map.put("ok","yes");
            /*管理员完成审批操作，可以开始推送审批完成消息了
            * 1.判断是否绑定微信
            * 2.绑定了就推送消息*/
            WeixinPushMsg weixinPushMsg = new WeixinPushMsgImpl();
            ApplyDao applyDao = new ApplyDaoImpl();
            Connection connection= BaseDao.getConnection();
            try {
                Map<String,String> applyMsg = applyDao.getApplyMsg(connection, applyID);
                if (applyMsg.get("openID")!=null){
                    weixinPushMsg.push_approvalMsg(applyMsg.get("openID"), WeixinConstants.APPROVAL_TEMPLATE_ID,applyMsg.get("labName"),
                            applyMsg.get("applyCount"),applyMsg.get("applyTime"),true);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*update：重置密码*/
    public void reset(HttpServletRequest req, HttpServletResponse resp,String userCode) throws IOException {
        RootService rootService = new RootServiceImpl();
        Map<String,Object> map = new HashMap<>();

        if (rootService.reset(userCode)>0){
            map.put("ok","yes");
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*update：删除用户*/
    public void delete(HttpServletRequest req, HttpServletResponse resp,String userCode) throws IOException {
        RootService rootService = new RootServiceImpl();
        Map<String,Object> map = new HashMap<>();

        if (rootService.delete(userCode)>0){
            map.put("ok","yes");
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*apply-details：通过labName获取labData*/
    public void getLabDataByLabName(HttpServletRequest req,HttpServletResponse resp,String labName) throws IOException {
        Map<String,Object> map=new HashMap<>();
        LabServiceImpl labService = new LabServiceImpl();

        map.put("labData",labService.getLabDataByLabName(labName));

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*personal：设置管理员留言*/
    public void setRootMsg(HttpServletRequest req,HttpServletResponse resp,String userCode,String rootMsg) throws IOException {
        RootService rootService = new RootServiceImpl();
        Map<String,Object> map = new HashMap<>();

        if (rootService.setRootMsg(userCode,rootMsg)>0){
            map.put("ok","yes");
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*labModify：设置实验室信息*/
    public void labModify(HttpServletRequest req,HttpServletResponse resp,String labName,String labTotal,String labTag,String labIntroduce) throws IOException {
        LabService labService = new LabServiceImpl();
        Map<String,Object> map = new HashMap<>();

        if (labService.labModify(labName,labTotal,labTag,labIntroduce)>0){
            map.put("ok","yes");
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*foot:获取预约申请数量*/
    public void getApplyCount(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        ApplyService applyService = new ApplyServiceImpl();
        Map<String,Object> map = new HashMap<>();

        map.put("applyCount",applyService.getApplyCount());

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*下载excel模板文件*/
    public void downloadFile(HttpServletRequest req,HttpServletResponse resp){
        try {
            // 1. 要获取下载文件的路径
            String realPath = Constants.EXCEL_FOLDER_TEMPLATE+"data.xlsx";
            // 2. 下载的文件名是啥？
            String fileName = realPath.substring(realPath.lastIndexOf(File.separator) + 1);
            // 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码，否则有可能乱码
            resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            // 4. 获取下载文件的输入流
            FileInputStream in = new FileInputStream(realPath);
            // 5. 创建缓冲区
            int len = 0;
            byte[] buffer = new byte[1024];
            // 6. 获取OutputStream对象
            ServletOutputStream out = resp.getOutputStream();
            // 7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端！
            while ((len=in.read(buffer))>0){
                out.write(buffer,0,len);
            }

            in.close();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }




    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
